﻿using CdhpyScheduler.Core;
using CdhpyScheduler.WebHost.PubMethod;
using Newtonsoft.Json;
using Quartz;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

namespace CdhpyScheduler.WebHost
{
    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            //Routes
            AreaRegistration.RegisterAllAreas();
            RouteConfig.RegisterRoutes(RouteTable.Routes);

            //Logger
            LoggerManager logger = new LoggerManager();
            log4net.ILog log = log4net.LogManager.GetLogger(typeof(IJob));
            HttpJob.Log = new Action<string>((str) => { log.Info(str); });
            log.Info("站点已启动");

            //Mapper
            AutoMapperConfiguration.Configure();

            //Jobs
            bool res = StartJobs(log);
            if(res)
            {
                log.Info("调度任务已启动");
            }
            else
            {
                log.Info("调度任务启动失败");
            }
        }

        private bool StartJobs(log4net.ILog log)
        {
            //load schedule jobs from confing file
            List<JobModel> jobs = new List<JobModel>();
            try
            {
                jobs = Job.LoadJobFromFile();
            }
            catch (Exception ex)
            {
                Console.Write(ex.Message);
                log.Error(ex.Message);
                return false;
            }

            //create jobs and start
            Job.jc.Create(jobs);
            Job.jc.Start();
            return true;
        }
    }
}
